# -*- coding: utf-8 -*-
from scrapy.exceptions import IgnoreRequest
from zc_core.dao.item_data_dao import ItemDataDao
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.http_util import retry_request
from zc_core.dao.batch_dao import BatchDao
from zc_core.util.done_filter import DoneFilter
from chdtp.rules import *
from zc_core.spiders.base import BaseSpider


class SaleSpider(BaseSpider):
    name = "sale"
    # 销量
    sales_url = 'https://www.chdtp.com/hdsc/wzgl/getHzdsxxCpzsAction.action'

    def __init__(self, batchNo=None, *args, **kwargs):
        super(SaleSpider, self).__init__(batchNo=batchNo, *args, **kwargs)
        # 创建批次记录
        BatchDao().create_batch(self.batch_no)
        # 避免重复采集
        self.done_filter = DoneFilter(self.batch_no)

    def start_requests(self):

        sku_list = ItemDataDao().get_batch_data_list(batch_no=self.batch_no, fields={'_id': 1, 'linkId': 1},
                                                     query={"$and":[{"soldCount": {"$exists": False}},{"catalog2Name": {"$in": ["办公设备", "办公耗材"]}}]})
        self.logger.info('全量: %s' % (len(sku_list)))
        for sku in sku_list:
            sku_id = sku.get("_id")
            link_id = sku.get("linkId")
            yield scrapy.FormRequest(
                url=self.sales_url,
                method='POST',
                meta={
                    'reqType': 'full',
                    'batchNo': self.batch_no,
                    'skuId': sku_id,
                },
                headers={
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                formdata={
                    'spxx.spxxidjmstr': link_id
                },
                callback=self.parse_sales,
                errback=self.error_back,
            )

    def parse_sales(self, response):
        meta = response.meta
        sku_id = meta.get("skuId")
        item = parse_item_count(response)
        if item and item.get('soldCount') >= 0:
            self.logger.info('销量: sku=%s, cnt=%s' % (sku_id, item.get('soldCount')))
            yield item
        else:
            self.logger.info('无销量: sku=%s' % sku_id)

